package com.yuxl.admin.manager.auth.socket.config;

import com.yuxl.admin.common.socket.config.WsProperties;
import com.yuxl.admin.manager.auth.socket.handler.WebSocketConnectionHandler;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.HandlerMapping;
import org.springframework.web.reactive.handler.SimpleUrlHandlerMapping;
import org.springframework.web.reactive.socket.server.support.WebSocketHandlerAdapter;

import java.util.HashMap;
import java.util.Map;

// 标记这个类为Spring配置类
@Slf4j
@Configuration
public class WebSocketConfig {

    @Resource
    private WsProperties wsProperties;


    // 配置WebSocket处理器的映射
    @Bean
    public HandlerMapping webSocketHandlerMapping(WebSocketConnectionHandler webSocketHandler) {
        log.debug("正在配置WebSocket处理器映射");
        // 创建一个映射，将路径"/ws"映射到我们的WebSocketHandler
        Map<String, WebSocketConnectionHandler> map = new HashMap<>();
        map.put(wsProperties.getConnectionPath()+"/**", webSocketHandler);

        // 创建一个SimpleUrlHandlerMapping实例
        SimpleUrlHandlerMapping handlerMapping = new SimpleUrlHandlerMapping();
        // 设置这个处理器映射的优先级
        handlerMapping.setOrder(-1);
        // 设置URL映射
        handlerMapping.setUrlMap(map);
        log.debug("WebSocket处理器映射已配置: {}", map);
        return handlerMapping;
    }

    // 配置WebSocketHandlerAdapter
    @Bean
    public WebSocketHandlerAdapter handlerAdapter() {
        log.debug("正在创建WebSocketHandlerAdapter");
        return new WebSocketHandlerAdapter();
    }
}